/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.alipay.demo.service.ImageUploadService;
import com.alipay.demo.service.ItemService;
import com.alipay.demo.util.AlipayApiCallback;
import com.alipay.demo.util.AlipayApiTemplate;
import com.alipay.demo.util.AlipaySdkUtil;
import com.alipay.demo.vo.ItemCreateRequest;
import com.alipay.demo.vo.OpenResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author jishupei.jsp
 * @version : ItemServiceImpl, v0.1 2024年05月11日 2:31 下午 jishupei.jsp Exp $
 */
@Service
public class ItemServiceImpl implements ItemService {

    private static final Logger logger = LogManager.getLogger(ItemServiceImpl.class);

    @Autowired
    private AlipaySdkUtil alipaySdkUtil;

    @Autowired
    private ImageUploadService imageUploadService;

    @Override
    public OpenResponse<List<AppxCategoryVO>> getCategories(String itemType, String catStatus) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<List<AppxCategoryVO>, AlipayOpenAppItemAllcategoryQueryResponse>() {
            @Override
            public AlipayOpenAppItemAllcategoryQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemAllcategoryQueryRequest request = new AlipayOpenAppItemAllcategoryQueryRequest();
                AlipayOpenAppItemAllcategoryQueryModel model = new AlipayOpenAppItemAllcategoryQueryModel();

                // 设置商品类型
                model.setItemType(itemType);

                model.setCatStatus(StringUtils.isEmpty(catStatus) ? "AUDIT_PASSED" : catStatus);

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public List<AppxCategoryVO> getData(AlipayOpenAppItemAllcategoryQueryResponse response) {
                List<CategoryAndParentVO> cats = response.getCats();
                if (CollectionUtils.isEmpty(cats)) {
                    return null;
                }
                List<AppxCategoryVO> childs = new ArrayList<>();
                for (CategoryAndParentVO cat : cats) {
                    if (CollectionUtils.isEmpty(cat.getCatAndParent())) {
                        continue;
                    }
                    // 获取叶子节点（cat_status不为空的是叶子结点）
                    Optional<AppxCategoryVO> categoryVO = cat.getCatAndParent().stream().filter(Objects::nonNull)
                            .filter(child -> StringUtils.areNotEmpty(child.getCatStatus())).findFirst();
                    categoryVO.ifPresent(childs::add);
                }
                return childs;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.allcategory.query";
            }
        });
    }

    @Override
    public OpenResponse<AlipayOpenAppItemTemplateQueryResponse> queryTemplate(String categoryId, String itemType) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppItemTemplateQueryResponse, AlipayOpenAppItemTemplateQueryResponse>() {
            @Override
            public AlipayOpenAppItemTemplateQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemTemplateQueryRequest request = new AlipayOpenAppItemTemplateQueryRequest();
                AlipayOpenAppItemTemplateQueryModel model = new AlipayOpenAppItemTemplateQueryModel();

                // 设置类目id
                model.setCategoryId(categoryId);

                model.setItemType(itemType);

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppItemTemplateQueryResponse getData(AlipayOpenAppItemTemplateQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.template.query";
            }
        });
    }

    @Override
    public OpenResponse<String> createSaleItem(ItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppItemCreateResponse>() {

            @Override
            public AlipayOpenAppItemCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemCreateRequest request = new AlipayOpenAppItemCreateRequest();
                AlipayOpenAppItemCreateModel model = getAlipayOpenAppItemCreateModel(param);

                // 设置商品模版类型
                model.setItemType("1");

                // 设置价格单元
                model.setPriceUnit("元");

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getImageList(), model.getItemType()));

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppItemCreateResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.create";
            }
        });
    }

    @Override
    public OpenResponse<String> createRentItem(ItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppItemCreateResponse>() {

            @Override
            public AlipayOpenAppItemCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemCreateRequest request = new AlipayOpenAppItemCreateRequest();
                AlipayOpenAppItemCreateModel model = getAlipayOpenAppItemCreateModel(param);

                // 设置商品模版类型
                model.setItemType("2");

                // 设置价格单元
                model.setPriceUnit("元/日");

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getImageList(), model.getItemType()));

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppItemCreateResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.create";
            }
        });
    }

    @Override
    public OpenResponse<String> createVirtualItem(ItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppItemCreateResponse>() {

            @Override
            public AlipayOpenAppItemCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemCreateRequest request = new AlipayOpenAppItemCreateRequest();
                AlipayOpenAppItemCreateModel model = getAlipayOpenAppItemCreateModel(param);

                // 设置商品模版类型
                model.setItemType("3");

                // 设置价格单元
                model.setPriceUnit("元");

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getImageList(), model.getItemType()));

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppItemCreateResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.create";
            }
        });
    }

    @Override
    public OpenResponse<String> updateItem(ItemCreateRequest param) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AlipayOpenAppItemModifyResponse>() {

            @Override
            public AlipayOpenAppItemModifyResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemModifyRequest request = new AlipayOpenAppItemModifyRequest();
                AlipayOpenAppItemCreateModel model = getAlipayOpenAppItemCreateModel(param);

                // 设置商品模版类型
                model.setItemType("1");

                // 设置价格单元
                model.setPriceUnit("元");

                // 设置属性列表
                model.setAttrs(getItemAttrs(param, model.getImageList(), model.getItemType()));

                request.setBizModel(model);
                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AlipayOpenAppItemModifyResponse response) {
                return response.getItemId();
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.modify";
            }
        });
    }

    @Override
    public OpenResponse<AlipayOpenAppItemQueryResponse> queryItemDetail(String itemId, String outItemId, long needEditSpu) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppItemQueryResponse, AlipayOpenAppItemQueryResponse>() {
            @Override
            public AlipayOpenAppItemQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemQueryRequest request = new AlipayOpenAppItemQueryRequest();
                AlipayOpenAppItemQueryModel model = new AlipayOpenAppItemQueryModel();
                if (!StringUtils.isEmpty(itemId)) {
                    // 设置支付宝侧商品id
                    model.setItemId(itemId);
                }

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧商品id
                    model.setOutItemId(outItemId);
                }

                // 设置是否查询编辑版本
                model.setNeedEditSpu(needEditSpu);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppItemQueryResponse getData(AlipayOpenAppItemQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.query";
            }
        });
    }

    @Override
    public OpenResponse<AlipayOpenAppItemListQueryResponse> queryItemList(String itemId, String outItemId, long pageNum, long pageSize) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AlipayOpenAppItemListQueryResponse, AlipayOpenAppItemListQueryResponse>() {
            @Override
            public AlipayOpenAppItemListQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AlipayOpenAppItemListQueryRequest request = new AlipayOpenAppItemListQueryRequest();
                AlipayOpenAppItemListQueryModel model = new AlipayOpenAppItemListQueryModel();

                if (!StringUtils.isEmpty(outItemId)) {
                    // 设置商家侧id列表
                    List<String> outItemIdList = new ArrayList<>();
                    outItemIdList.add(outItemId);
                    model.setOutItemIdList(outItemIdList);
                }

                if (!StringUtils.isEmpty(itemId)) {
                    // 设置平台侧商品id列表
                    List<String> itemIdList = new ArrayList<>();
                    itemIdList.add(itemId);
                    model.setItemIdList(itemIdList);
                }

                // 设置页码
                model.setPageNum(pageNum);
                // 设置单页大小
                model.setPageSize(pageSize);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public AlipayOpenAppItemListQueryResponse getData(AlipayOpenAppItemListQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "alipay.open.app.item.list.query";
            }
        });
    }

    private AlipayOpenAppItemCreateModel getAlipayOpenAppItemCreateModel(ItemCreateRequest param) throws AlipayApiException {
        AlipayOpenAppItemCreateModel model = new AlipayOpenAppItemCreateModel();

        // 设置商家侧商品ID
        model.setOutItemId(param.getOutItemId());

        // 设置商品名称
        model.setTitle(param.getProductName());

        // 设置导购描述
        model.setDesc(param.getProductName());

        // 设置商品主图
        model.setHeadImg(imageUploadService.uploadAndReturnId("file/head.jpg", "ITEM_HEAD_IMG"));

        // 设置商品图片的文件id列表
        List<String> imageList = new java.util.ArrayList<>();
        imageList.add(imageUploadService.uploadAndReturnId("file/head.jpg", "ITEM_IMAGE_LIST"));
        model.setImageList(imageList);

        // 设置商品详情页URL，需要先完成商品详情页组件开发接入
        try {
            String url = "plugin-private://2021003177653028/pages/goodsDetail/goodsDetail?outItemId=" + param.getOutItemId();
            model.setPath("alipays://platformapi/startApp?appId=" + alipaySdkUtil.getAppId()
                    + "&page=" + URLEncoder.encode(url, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new AlipayApiException("url解析失败");
        }

        // 设置类目ID
        model.setCategoryId(param.getCategoryId());

        // 设置商品售价
        model.setSalePrice(1L);

        // 设置商品原价
        model.setOriginalPrice(1000L);

        // 设置库存
        model.setStockNum(100L);

        // 设置商品售卖状态
        model.setSaleStatus("AVAILABLE");

        return model;
    }

    private List<AttributeVO> getTemplateItemAttrs(String categoryId, String itemType) throws AlipayApiException {
        OpenResponse<AlipayOpenAppItemTemplateQueryResponse> templateResponse = queryTemplate(categoryId, itemType);
        if (!"10000".equals(templateResponse.getCode())) {
            throw new AlipayApiException("查询普通商品模板失败");
        }

        if (templateResponse.getData().getAttr() == null) {
            return null;
        }

        return templateResponse.getData().getAttr().getItemAttrList();
    }

    private List<AppItemAttrVO> getItemAttrs(ItemCreateRequest param, List<String> imageList, String itemType) throws AlipayApiException {
        List<AttributeVO> attributes = getTemplateItemAttrs(param.getCategoryId(), itemType);
        if (CollectionUtils.isEmpty(attributes)) {
            return null;
        }
        List<AppItemAttrVO> attrs = new ArrayList<>();
        for (AttributeVO attr : attributes) {
            AppItemAttrVO appItemAttrVO = new AppItemAttrVO();
            appItemAttrVO.setAttrKey(attr.getKey());

            switch (attr.getKey()) {
                // -----BEGIN 普通实物类商品可传入以下属性 -----
                case "delivery_info":
                    // 商品履约信息
                    if (StringUtils.isEmpty(param.getDeliveryId())) {
                        break;
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("delivery_id", param.getDeliveryId());
                    jsonObject.put("shop_ids", param.getShopIds());
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(jsonObject);
                    appItemAttrVO.setAttrValue(JSONArray.toJSONString(jsonArray));
                    break;
                case "selling_point_tag":
                    // 导购标签
                    appItemAttrVO.setAttrValue("[\"鲜花\",\"盆栽\"]");
                    break;
                case "white_ground_image":
                    // 商品白底图
                    JSONObject image = new JSONObject();
                    image.put("url_list", imageList);
                    appItemAttrVO.setAttrValue(image.toJSONString());
                    break;
                case "shipping_time_limit":
                    // 现货发货时效
                    appItemAttrVO.setAttrValue("1");
                    break;
                // -----END 普通实物类商品可传入以上属性 -----

                // -----BEGIN 租赁类商品可传入以下属性 -----
                case "rent_from_numbers_of_day":
                    // 起租天数
                    appItemAttrVO.setAttrValue("3");
                    break;
                case "item_fineness":
                    // 商品成色
                    appItemAttrVO.setAttrValue("secondHand");
                    break;
                case "whether_support_free_deposit":
                    // 是否支持免押
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "whether_continue_rent":
                    // 是否可续租
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "whether_buyout":
                    // 是否可买断
                    appItemAttrVO.setAttrValue("1");
                    break;
                // -----END 租赁类商品可传入以上属性 -----

                // -----BEGIN 虚拟类(电影/演出/体育赛事/休闲娱乐/运动健身类目)商品可传入以下属性 -----
                case "sale_time":
                    // 开售时间，明天16:00:00开始
                    appItemAttrVO.setAttrValue(LocalDateTime.now()
                            .plusDays(1)
                            .withHour(16)
                            .withMinute(0)
                            .withSecond(0)
                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    break;
                case "performance_date_range":
                    // 演出日期
                    JSONObject range = new JSONObject();
                    LocalDateTime localDateTime = LocalDateTime.now()
                            .plusMonths(1);
                    // 一个月后开始
                    range.put("start_date", localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    range.put("end_date", localDateTime
                            .plusDays(1)
                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    appItemAttrVO.setAttrValue(range.toJSONString());
                    break;
                case "agent_type":
                    // 票务代理类型
                    appItemAttrVO.setAttrValue("1");
                    break;
                case "performance_area":
                    // 演出举办地区
                    appItemAttrVO.setAttrValue("{\"city_code\":\"120100\"}");
                    break;
                case "venue_name":
                    // 演出场馆名称
                    appItemAttrVO.setAttrValue("蚂蚁A空间");
                    break;
                case "post_img":
                    // 演出海报（图片）
                    JSONObject image2 = new JSONObject();
                    image2.put("url_list", imageList);
                    appItemAttrVO.setAttrValue(image2.toJSONString());
                    break;
                // -----END 虚拟类(电影/演出/体育赛事/休闲娱乐/运动健身类目)商品可传入以上属性 -----
            }
            if (!StringUtils.isEmpty(appItemAttrVO.getAttrValue())) {
                attrs.add(appItemAttrVO);
            }
        }
        return attrs;
    }
}
